#! /usr/bin/perl
#
# file tool
# serpmelon
#
package File;

use Cwd;

sub new {
    my $class = shift;
    my $arg = shift;
    unless(-e $arg) {
        die "Illegal file! $arg \n";
    }

    my $fileRef = parse($arg);
    my $this = {
        _rawFile => $arg,
        _filename => $fileRef->{filename},
        _basePath => $fileRef->{basePath},
        _suffix => $fileRef->{suffix}
    };

    return bless $this, $class;
}

sub suffix{
    my $this = shift;
    $this->{_suffix};
}

sub filename{
    my $this = shift;
    $this->{_filename};
}

sub basePath{
    my $this = shift;
    $this->{_basePath};
}

sub parse {
    
    my $file = shift;
    my $first = substr $file, 0, 1;
    my $basePath = "";
    my $filename = "";
    my $suffix = "";
    if($first eq '/') {
        my @arr = split /\//, $file;
        pop @arr;
        $basePath = join '/', @arr;
    } else {
        $basePath = cwd();
    }
    $basePath =~ s/ /\\ /g;

    my @arr = split /\./, $file;
    my $arrSize = scalar @arr;
    if($arrSize == 1){
        $filename = (split '/', $file)[-1];
    } else {
        $suffix = $arr[-1];
        $filename = (split '/', $arr[0])[-1];
    }

    return {'filename' => $filename,
                  'suffix' => $suffix,
                  'basePath' => $basePath};
}

sub fullPath {
    my $this = shift;
    my $result = $this->{_basePath} . '/' . $this->{_filename};
    if($this->{_suffix}) {
        $result = $result . '.' . $this->{_suffix};
    }

    $result;
}

sub size {
    my $this = shift;
    my $size = -s $this->{_rawFile};
    return $size;
}

# change extension
# the first argument is source file
# the second argument is new extension name;
sub changeExtension{
    my $sourceFile = $_[0];
    my $newExtension = $_[1];

    unless($sourceFile && $newExtension){
        die "arguments are illegal! source file = $sourceFile, new extension = $newExtension. \n";
    }

    my @arr = split /\./, $sourceFile;
    if(scalar @arr == 1) {
        die "source file`s name illegal, $sourceFile, \n";
    }

    pop @arr;
    push @arr, $newExtension;
    my $result = join ".", @arr;

    return $result;
}

1;
